package com.caiyi.financial.nirvana.sms.gateway.sgip;

import com.caiyi.financial.nirvana.sms.gateway.sgip.message.Message;
import io.netty.buffer.ByteBuf;

/**
 * CMPP消息头
 */
public class SGIPHeader implements Message {
    //消息头长度 byte
    public final static int HEADER_LENGTH = 20;
    protected int totalLength;
    protected int commandID;
    //源节点编号、日期时间、编号三部分组成序列号
    protected int spNodeNum;
    protected int timestamp;
    protected int sequenceId;

    public int getTotalLength() {
        return totalLength;
    }

    public void setTotalLength(int totalLength) {
        this.totalLength = totalLength;
    }

    public int getCommandID() {
        return commandID;
    }

    public void setCommandID(int commandID) {
        this.commandID = commandID;
    }

    public int getSpNodeNum() {
        return spNodeNum;
    }

    public void setSpNodeNum(int spNodeNum) {
        this.spNodeNum = spNodeNum;
    }

    public int getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(int timestamp) {
        this.timestamp = timestamp;
    }

    public int getSequenceId() {
        return sequenceId;
    }

    public void setSequenceId(int sequenceId) {
        this.sequenceId = sequenceId;
    }

    //消息唯一序列号，日期时间+编号，内部使用
    public long getMessageId() {
        return (long) timestamp * 10000 + sequenceId;
    }

    /**
     * 消息头编码
     */
    @Override
    public int encode(ByteBuf buffer) {
        int length = 0;
        buffer.writeInt(this.totalLength);
        length += 4;
        buffer.writeInt(this.commandID);
        length += 4;
        buffer.writeInt(this.spNodeNum);
        length += 4;
        buffer.writeInt(this.timestamp);
        length += 4;
        buffer.writeInt(this.sequenceId);
        length += 4;
        return length;
    }

    /**
     * 消息头解码
     */
    @Override
    public SGIPHeader decode(ByteBuf buffer) {
        setTotalLength(buffer.readInt());
        setCommandID(buffer.readInt());
        setSpNodeNum(buffer.readInt());
        setTimestamp(buffer.readInt());
        setSequenceId(buffer.readInt());
        return this;
    }
}
